package io.github.biezhi.elves.service.impl;

import java.util.List;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import io.github.biezhi.elves.utils.HttpUtil;
import io.github.biezhi.elves.utils.StringUtils;
import io.github.biezhi.elves.model.EbaseInfo;
import org.springframework.stereotype.Service;
import io.github.biezhi.elves.model.RelationProfileInfo;
import io.github.biezhi.elves.mapper.ShareholderMapper;
import io.github.biezhi.elves.service.RelationProfileService;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 关联图谱信息接口实现类
 *
 */
@Service("relationProfileService")
public class RelationProfileServiceImpl implements RelationProfileService {
	@Autowired
	private ShareholderMapper shareholderMapper;
	
	/**
	 * 解析json数据并保存关联图谱信息数据入库
	 * @param cmsAsynUrl
	 * @param jsonStr
	 * @param unique
	 * @param entname
	 * @param requestEntnameVal
	 */
	public void saveRelationProfileData(String cmsAsynUrl,String jsonStr,String unique,String entname,String requestEntnameVal){
		String resultJson = "";
		try {
			JSONObject json = JSONObject.parseObject(jsonStr);
			if(json.containsKey("success")) {
				JSONObject resultSuccessObject = JSONObject.parseObject(json.getString("success"));
				if(resultSuccessObject.containsKey("results")){
					JSONObject resultsObject = null;
					String resultsJson = resultSuccessObject.getString("results");
					if(resultsJson.indexOf("[")==0) {
						JSONArray resultsArrayObject = JSONArray.parseArray(resultsJson);
						resultsObject = JSONObject.parseObject(resultsArrayObject.getString(0));
					} else {
						resultsObject = JSONObject.parseObject(resultsJson);
					}
					if(resultsObject.containsKey("data") && resultsObject.get("data")!=null) {
						JSONObject resultsGraphObject = null;
						String resultsDataJson = resultsObject.getString("data");
						if(resultsDataJson.indexOf("[")==0) {
							JSONArray resultsDataArrayObject = JSONArray.parseArray(resultsDataJson);
							resultsGraphObject = JSONObject.parseObject(resultsDataArrayObject.getString(0));
						} else {
							resultsGraphObject = JSONObject.parseObject(resultsDataJson);
						}
						if(resultsGraphObject.containsKey("graph") && resultsGraphObject.get("graph")!=null) {
							JSONObject resultsNodesObject = JSONObject.parseObject(resultsGraphObject.getString("graph"));
							if(resultsNodesObject.containsKey("nodes") && resultsNodesObject.get("nodes")!=null) {
								if(resultJson.indexOf("[")==0) {
									resultJson = resultsNodesObject.getString("nodes");
								} else {
									RelationProfileInfo relationProfileInfo = null;
									resultJson = resultsNodesObject.getString("nodes");
									JSONArray nodesArray = JSONArray.parseArray(resultJson);
									List<EbaseInfo> ebaseInfoList = shareholderMapper.queryEbaseInfoByEntname(entname);
									
									if(ebaseInfoList!=null && ebaseInfoList.size()>0 && nodesArray!=null){
										for(EbaseInfo ebaseInfo : ebaseInfoList){
											if(!StringUtils.isNullOrEmpty(unique)){
												relationProfileInfo.setUniqueId(unique);
											}
											relationProfileInfo.setPripid(ebaseInfo.getPripid());
											//企业名称
											relationProfileInfo.setEntname(entname);
											//地市Id
											relationProfileInfo.setCityId(ebaseInfo.getCityId());
											
											for (int i = 0; i < nodesArray.size(); i++) {
												JSONObject resultJsonObject = new JSONObject();
												JSONObject nodeJsonObject = nodesArray.getJSONObject(i);
												resultJsonObject.putAll(nodeJsonObject);
												
//												String nodeJsonStr = nodeJsonObject.toJSONString();
												String nodeJsonStr = resultJsonObject.toJSONString();
												relationProfileInfo = JSON.parseObject(nodeJsonStr, RelationProfileInfo.class);
												if(nodeJsonObject.containsKey("properties")) {
													JSONObject propertiesJsonObject = JSONObject.parseObject(nodeJsonObject.getString("properties"));
//													propertiesJsonObject.putAll(nodeJsonObject);
													resultJsonObject.putAll(propertiesJsonObject);
													
//													String propertiesJsonStr = propertiesJsonObject.toJSONString();
													String propertiesJsonStr = resultJsonObject.toJSONString();
													relationProfileInfo = JSON.parseObject(propertiesJsonStr, RelationProfileInfo.class);
												}
												//保存关联图谱信息
												shareholderMapper.saveRelationProfileInfo(relationProfileInfo);
												try {
													if(resultsNodesObject.containsKey("relationships") && resultsNodesObject.get("relationships")!=null){
														JSONArray relationshipsArray = resultsNodesObject.getJSONArray("relationships");
													
														for (int k = 0; k < relationshipsArray.size(); k++) {
															JSONObject relationshipsJsonObject = relationshipsArray.getJSONObject(k);
															resultJsonObject.putAll(relationshipsJsonObject);
															
//															String relationshipsJsonStr = relationshipsJsonObject.toJSONString();
															String relationshipsJsonStr = resultJsonObject.toJSONString();
															relationProfileInfo = JSON.parseObject(relationshipsJsonStr, RelationProfileInfo.class);
															
															if(nodeJsonObject.containsKey("properties")) {
																JSONObject propertiesJsonObject = JSONObject.parseObject(nodeJsonObject.getString("properties"));
																resultJsonObject.putAll(propertiesJsonObject);
																
																String propertiesJsonStr = resultJsonObject.toJSONString();
																relationProfileInfo = JSON.parseObject(propertiesJsonStr, RelationProfileInfo.class);
															}
															
															if(!StringUtils.isNullOrEmpty(unique)){
																relationProfileInfo.setUniqueId(unique);
															}
															//企业名称
															relationProfileInfo.setEntname(entname);
															
															System.out.println("关联图谱信息循环体{{}}==>json转换对象数据{{}}==>" + relationProfileInfo);
															//保存关联图谱信息
															shareholderMapper.saveRelationProfileInfo(relationProfileInfo);
														}
													}
												} catch (Exception e) {
													e.printStackTrace();
												}
											}
										}
									}else{
										relationProfileInfo = JSON.parseObject(resultJson, RelationProfileInfo.class);
										
										if(!StringUtils.isNullOrEmpty(unique)){
											relationProfileInfo.setUniqueId(unique);
										}
										//企业名称
										relationProfileInfo.setEntname(entname);
										System.out.println("关联图谱信息非循环体{{}}==>json转换对象数据{{}}==>" + relationProfileInfo);
										//保存关联图谱信息
										shareholderMapper.saveRelationProfileInfo(relationProfileInfo);
									}
								}
							}
						}
					}
				}
			}
			
//			if(resultJsonObject.containsKey("Children") && resultJsonObject.get("Children")!=null){
//				JSONArray array = resultJsonObject.getJSONArray("Children");
//				for (int i = 0; i < array.size(); i++) {
//					JSONObject arrJsonObject = array.getJSONObject(i);
//					String arrJsonStr = arrJsonObject.toJSONString();
//					relationProfileInfo = JSON.parseObject(arrJsonStr, RelationProfileInfo.class);
//					if(!StringUtils.isNullOrEmpty(unique)){
//						relationProfileInfo.setUniqueId(unique);
//					}
//					//企业名称
//					relationProfileInfo.setEntname(entname);
//					System.out.println("关联图谱信息循环体{{}}==>json转换对象数据{{}}==>" + relationProfileInfo);
//					//保存关联图谱信息
//					shareholderMapper.saveRelationProfileInfo(relationProfileInfo);
//				    if(arrJsonObject.containsKey("Children") && (arrJsonObject.get("Children")!=null || !"null".equals(arrJsonObject.get("Children").toString()))){
//				    	//解析关联图谱信息子json数据
//				    	saveRelationProfileChildrenData(arrJsonObject.get("Children").toString(),unique,entname);
//				    }
//				}
//			}
		} catch (Exception e) {
			System.err.println("io.github.biezhi.elves.service.impl.RelationProfileServiceImpl.saveRelationProfileData，解析json数据并保存关联图谱信息数据入库异常，cmsAsynUrl链接为:" + cmsAsynUrl + "，json串为:" + jsonStr + "，异常信息{{}}==>" + StringUtils.getErrorInfoFromException(e));
			
			System.out.println("io.github.biezhi.elves.service.impl.RelationProfileServiceImpl.saveRelationProfileData，休眠5000毫秒后，重新再调用......");
			try {
				Thread.sleep(5000);
				System.out.println("io.github.biezhi.elves.service.impl.RelationProfileServiceImpl.saveRelationProfileData，已休眠5000毫秒，开始重新再调用saveRelationProfileData方法===>");
				System.err.println("企业名称{{}}==>" + entname);
				//返回响应url内容
				jsonStr = HttpUtil.getQccGetHttpReponseBody(cmsAsynUrl);
				saveRelationProfileData(cmsAsynUrl,jsonStr, unique, entname, requestEntnameVal);
			} catch (InterruptedException e1) {
				e1.printStackTrace();
			}
		}
	}
	
	/**
	 * 解析关联图谱信息子json数据
	 * @param jsonStr
	 * @param unique
	 * @param entname
	 */
	private void saveRelationProfileChildrenData(String jsonStr,String unique,String entname){
		try{
			JSONArray array = JSONArray.parseArray(jsonStr);
			if(array!=null){
				for (int i = 0; i < array.size(); i++) {
					JSONObject arrJsonObject = array.getJSONObject(i);
					String arrJsonStr = arrJsonObject.toJSONString();
					RelationProfileInfo relationProfileInfo = JSON.parseObject(arrJsonStr, RelationProfileInfo.class);
					if(!StringUtils.isNullOrEmpty(unique)){
						relationProfileInfo.setUniqueId(unique);
					}
					//企业名称
					relationProfileInfo.setEntname(entname);
					System.out.println("股权结构图子循环体{{}}==>json转换对象数据{{}}==>" + relationProfileInfo);
					try {
						//保存股权结构图
						shareholderMapper.saveRelationProfileInfo(relationProfileInfo);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}catch(Exception e){
			System.err.println("io.github.biezhi.elves.service.impl.RelationProfileServiceImpl.saveRelationProfileChildrenData，解析子json数据并保存关联图谱信息数据入库异常，json串为:" + jsonStr + "{{}}==>" + StringUtils.getErrorInfoFromException(e));
			
			System.out.println("io.github.biezhi.elves.service.impl.RelationProfileServiceImpl.saveRelationProfileChildrenData，休眠5000毫秒后，重新再调用......");
			try {
				Thread.sleep(5000);
				
				System.out.println("io.github.biezhi.elves.service.impl.RelationProfileServiceImpl.saveRelationProfileChildrenData，已休眠5000毫秒，开始重新再调用saveRelationProfileChildrenData方法===>");
				saveRelationProfileChildrenData(jsonStr, unique, entname);
			} catch (InterruptedException e1) {
				e1.printStackTrace();
			}
		}
	}
}